package com.cheboohui.iqs.spider.login;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONObject;
import com.cheboohui.iqs.common.read.PropertyUtils;
import com.cheboohui.iqs.http.tool.HttpClient;

/**
 * 平安爬虫登录类
 * 
 * @author xielonghai
 *
 */
public class Login {

	/**
	 * logger:日志工具.
	 */
	private static Log log = LogFactory.getLog(Login.class);

	/**
	 * 平安爬虫登录后页面跳转第二步
	 */
	private static final String urlTwo = "https://icore-pts.pingan.com.cn/ebusiness";

	/**
	 * 平安爬虫登录后页面跳转第三步
	 */
	private static final String urlThree = "https://icore-pts.pingan.com.cn/ebusiness/auto/newness/toibcswriter.do?transmitId=apply";

	/**
	 * 记录登录平安次数
	 */
	private static int loginNum = 1;

	/**
	 * 取得平安登录url
	 * 
	 * @return
	 */
	private static String getLoginUrl() {
		return "https://icore-pts.pingan.com.cn/ebusiness/j_security_check?SMAUTHREASON="
				+ PropertyUtils.readSpringboot("config.properties", "SMAUTHREASON") + "&j_username="
				+ PropertyUtils.readSpringboot("config.properties", "j_username") + "&j_password="
				+ PropertyUtils.readSpringboot("config.properties", "j_password") + "&randCode="
				+ PropertyUtils.readSpringboot("config.properties", "randCode");
	}

	/***
	 * 登录平安
	 */
	public static boolean login(CloseableHttpClient httpClient, HttpClientContext httpContext) {
		try {
			log.info("第" + loginNum + "次,开始登录平安(爬虫)...");

			HttpClient._httpGetToBody(httpClient, httpContext, getLoginUrl());

			HttpClient._httpGetToBody(httpClient, httpContext, urlTwo);

			HttpGet httpGet = new HttpGet(urlThree);
			CloseableHttpResponse response3 = httpClient.execute(httpGet, httpContext);
			String three = EntityUtils.toString(response3.getEntity());
			String cookie = "";
			List<Cookie> lc = httpContext.getCookieStore().getCookies();
			for (int i = 0; i < lc.size(); i++) {
				if (lc.get(i).getName().equals("BIGipServericore-pts_http_DMZ_PrdPool"))
					cookie = cookie + "BIGipServerICORE-PNBS_DMZ_PrdPool=" + lc.get(i).getValue() + ";";
				else if (lc.get(i).getName().equals("WLS_HTTP_BRIDGE_ICOREPTS"))
					cookie = cookie + "JSESSIONID=" + lc.get(i).getValue() + ";";
				else if (lc.get(i).getName().equals("_WL_AUTHCOOKIE_WLS_HTTP_BRIDGE_ICOREPTS"))
					cookie = cookie + "_WL_AUTHCOOKIE_JSESSIONID=tfwVcyMd-wJavwFk-EL-=" + lc.get(i).getValue();
			}

			// String form =
			// Jsoup.parse(three).getElementById("workbenchIBCSAppForm").toString();
			String sixUrl = Jsoup.parse(three).getElementById("workbenchIBCSAppForm").attr("action");
			/// form.substring(form.indexOf("action") + 8, form.indexOf(">") -
			/// 1);

			HttpPost httpPost = new HttpPost(sixUrl);
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(getFourParam(three), Consts.UTF_8);
			httpPost.setEntity(entity);
			httpPost.setHeader("Cookie", cookie);
			httpPost.setHeader("Origin", " https://icore-pts.pingan.com.cn");
			httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
			httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
			httpPost.setHeader("Upgrade-Insecure-Requests", "1");
			httpPost.setHeader("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
			httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			httpPost.setHeader("Cache-Control", "max-age=0");
			httpPost.setHeader("Referer",
					"https://icore-pts.pingan.com.cn/ebusiness/auto/newness/toibcswriter.do?transmitId=apply");
			httpPost.setHeader("Connection", "keep-alive");
			CloseableHttpResponse response = httpClient.execute(httpPost, httpContext);

			try {
				String html = EntityUtils.toString(response.getEntity());
				html = html.substring(html.indexOf("outSystemDateMap"));
				html = html.substring(html.indexOf("{"));
				html = html.substring(0, html.indexOf(";"));
				JSONObject json = JSONObject.parseObject(html);

				JSONObject postParams = json.getJSONObject("postParams");
				String urls = "https://icorepnbs.pingan.com.cn/icore_pnbs/do/app/cache/switch/preQuoteValidate?departmentCode="
						+ postParams.getString("departmentCode") + "&businessSourceCode="
						+ postParams.getString("businessSourceCode") + "&businessSourceDetailCode="
						+ postParams.getString("businessSourceDetailCode") + "&channelSourceCode="
						+ postParams.getString("channelSourceCode") + "&channelSourceDetailCode="
						+ postParams.getString("channelSourceDetailCode");

				HttpClient._httpGetToBody(httpClient, httpContext, urls);

			} finally {
				response.close();
			}
			loginNum++;
			return true;
		} catch (Exception e) {
			log.info("第" + loginNum + "次,登录平安(爬虫)异常<报错>:" + e);
			loginNum++;
			return false;
		}
	}

	/**
	 * 获取第四步POST请求参数
	 * 
	 * @param three
	 *            第三步返回html
	 * @return
	 */
	private static ArrayList<BasicNameValuePair> getFourParam(String three) {

		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();

		Elements inputs = Jsoup.parse(three).getElementById("workbenchIBCSAppForm").select("input");
		for (Element input : inputs) {
			if ("text".equals(input.attr("type"))) {
				params.add(new BasicNameValuePair(input.attr("name"), input.attr("value")));
			}
		}

		// params.add(new BasicNameValuePair("systemId", "ICORE-PTS"));
		// params.add(new BasicNameValuePair("transferId", "apply"));
		// params.add(new BasicNameValuePair("timestamp", getValue(three,
		// "timestamp")));
		// params.add(new BasicNameValuePair("umCode", "CQHRBXDL-00002"));
		// params.add(new BasicNameValuePair("userName", "重庆华瑞保险代理"));
		// params.add(new BasicNameValuePair("cypherText", getValue(three,
		// "cypherText")));
		// params.add(new BasicNameValuePair("isUseCyberArk", "Y"));
		// params.add(new BasicNameValuePair("partnerType", "0"));
		// params.add(new BasicNameValuePair("agentCode", "18000290"));
		// params.add(new BasicNameValuePair("partnerWorkNetCode", ""));
		// params.add(new BasicNameValuePair("operablePartnerWorknetList",
		// "218101408008"));
		// params.add(new BasicNameValuePair("businessSourceCode", "2"));
		// params.add(new BasicNameValuePair("businessSourceDetailCode", "3"));
		// params.add(new BasicNameValuePair("channelSourceCode", "G"));
		// params.add(new BasicNameValuePair("channelSourceDetailCode", "F"));
		// params.add(new BasicNameValuePair("transitSystemSource",
		// "ICORE-PTS"));
		// params.add(new BasicNameValuePair("dataSource", "ICORE-PTS"));
		// params.add(new BasicNameValuePair("departmentCode", "21825"));
		// params.add(new BasicNameValuePair("saleAgentName", "张烨"));
		// params.add(new BasicNameValuePair("saleAgentCode", "2180001463"));
		// params.add(new BasicNameValuePair("brandDetail", ""));
		// params.add(new BasicNameValuePair("BrandDetailName", ""));
		// params.add(new BasicNameValuePair("dealerCodes", ""));
		// params.add(new BasicNameValuePair("agentSalerNameText", ""));
		// params.add(new BasicNameValuePair("businessCertificateNumText", ""));
		// params.add(new BasicNameValuePair("empBusinessCertificateNumText",
		// ""));
		// params.add(new BasicNameValuePair("brokerCode", ""));
		// params.add(new BasicNameValuePair("relationQueryFlag", "Y"));
		// params.add(new BasicNameValuePair("departmentCodeList", ""));
		return params;
	}

	/**
	 * @param html
	 *            html文件
	 * @param id
	 *            id
	 * @return
	 */
	// private static String getValue(String html, String id) {
	// Document doc = Jsoup.parse(html);
	// return doc.getElementById(id).val();
	// }
}
